package com.wolfking.jeesite.controller;

import com.google.common.collect.Maps;
import com.wolfking.jeesite.config.SsoConfig;
import com.wolfking.jeesite.entity.*;
import com.wolfking.jeesite.event.AbstractSignEvent;
import com.wolfking.jeesite.exception.JeesiteException;
import com.wolfking.jeesite.service.DictService;
import com.wolfking.jeesite.service.OfficeService;
import com.wolfking.jeesite.service.RoleService;
import com.wolfking.jeesite.service.UserService;
import com.wolfking.jeesite.sign.LoginUser;
import com.wolfking.jeesite.sign.Sign;
import com.wolfking.jeesite.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 用户的controller
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年5月6日 下午9:01:37
 * @copyright wolfking
 */
@Slf4j
@Controller
@RequestMapping("/sys/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    @Autowired
    private SsoConfig ssoConfig;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private RoleService roleService;

    /**
     * 用户修改密码页面的GET
     *
     * @return
     */
    @Sign
    @RequestMapping(value = "/modifyPwd", method = RequestMethod.GET)
    public String modifyPwdGet() {
        return "sys/user/modifyPwd";
    }

    /**
     * 用户修改密码的操作
     *
     * @param user
     * @return
     */
    @Sign
    @RequestMapping(value = "/modifyPwd", method = RequestMethod.POST)
    public String modifyPwdPost(@LoginUser User user, @RequestParam String oldPassword,
                                @RequestParam String newPassword, RedirectAttributes redirectAttributes) {
        try {
            userService.modifyPwd(user.getId(), oldPassword, newPassword);
            redirectAttributes.addFlashAttribute("message", "用户修改密码成功");
            return ssoConfig.getRedirectWithPath("/sys/user/userInfo");
        } catch (Exception e) {
            try {
                log.error("", e);
                JeesiteException ex = JeesiteException.parse(e);
                redirectAttributes.addFlashAttribute("message", ex.getMessage());
            } catch (Exception ee) {
                log.error("", e);
                redirectAttributes.addFlashAttribute("message", "用户修改密码异常");
            }
            return ssoConfig.getRedirectWithPath("/sys/user/modifyPwd");
        }
    }

    /**
     * 用户个人信息页面
     *
     * @param model
     * @param user
     * @return
     */
    @Sign
    @RequestMapping(value = "/userInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public String infoPost(Model model, User user, @LoginUser User current, HttpServletRequest request) {
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            userService.updateUserInfo(user);
            model.addAttribute("message", "修改用户信息成功");
        }
        user = userService.getById(current.getId());
        List<Dict> dicts = dictService.getByType("sys_user_type");
        Office office = officeService.getById(user.getOfficeId());
        Office company = officeService.getById(user.getCompanyId());
        model.addAttribute("dicts", dicts);
        model.addAttribute("user", user);
        model.addAttribute("office", office);
        model.addAttribute("company", company);
        return "sys/user/userInfo";
    }

    /**
     * 用户的编辑页面
     *
     * @param model
     * @param id
     * @return
     */
    @Sign(code = "sys:user:view")
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editGet(Model model, @RequestParam(required = false) Integer id) {
        User user = new User();
        Office office = new Office();
        Office company = new Office();
        if (Objects.nonNull(id))
            user = userService.getById(id);
        model.addAttribute("user", user);
        List<Dict> typeDicts = dictService.getByType("sys_user_type");
        model.addAttribute("typeDicts", typeDicts);
        List<Dict> loginDicts = dictService.getByType("yes_no");
        model.addAttribute("loginDicts", loginDicts);
        if (Objects.nonNull(id)) {
            office = officeService.getById(user.getOfficeId());
            company = officeService.getById(user.getCompanyId());
        }
        model.addAttribute("office", office);
        model.addAttribute("company", company);
        List<Role> roles = roleService.list();
        model.addAttribute("roles", roles);
        model.addAttribute("roleIds", roleService.getUserRoleIds(user.getId()));
        return "sys/user/edit";
    }


    /**
     * 用户的编辑页面
     *
     * @param model
     * @param id
     * @return
     */
    @Sign(code = "sys:user:view")
    @RequestMapping(value = "/copyEdit", method = RequestMethod.GET)
    public String copyEdit(Model model, Integer id) {
        String view = editGet(model, id);
        User user = (User) model.getAttribute("user");
        if (Objects.nonNull(user) && Objects.nonNull(user.getId())) {
            user.setLoginName(user.getLoginName() + "-2");
            user.setPassword(null);
            user.setEmail(user.getEmail() + "-2");
            user.setPhone(user.getPhone() + "-2");
            user.setRemarks(user.getRemarks() + "-2");
            user.setName(user.getName() + "-2");
            user.setId(null);
            user.setCreateTime(null);
            user.setUpdateTime(null);
            user.setVersion(0);
        }
        return view;
    }

    /**
     * 用户修改
     *
     * @param user
     * @param redirectAttributes
     * @return
     */
    @Sign(code = "sys:user:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String editPost(User user, RedirectAttributes redirectAttributes,
                           @RequestParam(required = false) String newPassword) {
        //确保管理员的角色永不消失
        if (Objects.nonNull(user.getId()) && user.getId().equals(1)) {
            user.getRoleIdList().add(1);
        }
        if (StringUtils.isNotBlank(newPassword)) {
            user.setPassword(PasswordUtil.entryptPassword(newPassword));
        }
        if (Objects.nonNull(user.getId())) {
            userService.updateById(user);
            redirectAttributes.addFlashAttribute("message", "修改用户成功");
        } else {
            userService.save(user);
            redirectAttributes.addFlashAttribute("message", "添加用户成功");
        }
        return ssoConfig.getRedirectWithPath("/sys/user/list");
    }

    /**
     * 用户列表页
     *
     * @param model
     * @param user
     * @return
     */
    @Sign(code = "sys:user:view")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String list(Model model, User user, @RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "20") int pageSize) {
        Office office = new Office();
        Office company = new Office();
        if (Objects.nonNull(user.getOfficeId()))
            office = officeService.getById(user.getOfficeId());
        if (Objects.nonNull(user.getCompanyId()))
            company = officeService.getById(user.getCompanyId());
        model.addAttribute("office", office);
        model.addAttribute("company", company);
        Map<String, String> officeMap = Maps.newHashMap();
        List<Office> offices = officeService.list();
        for (Office o : offices)
            officeMap.put(o.getId() + "", o.getName());
        model.addAttribute("officeMap", officeMap);
        PageInfo<User> page = userService.pageLike(user, pageNum, pageSize);
        model.addAttribute("page", page);
        return "sys/user/list";
    }

    /**
     * 用户的index主页
     *
     * @return
     */
    @Sign(code = "sys:user:view")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String userIndex() {
        return "sys/user/index";
    }

    //删除用户和角色的关联，用户和office的关联
    @Sign
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam Integer id, RedirectAttributes redirectAttributes, @LoginUser User user) {
        if (user.getId().equals(id)) {
            redirectAttributes.addFlashAttribute("message",
                    "自己不能删除自己");
            redirectAttributes.addFlashAttribute("messageType", "warning");
        } else if (id.equals(1)) {
            redirectAttributes.addFlashAttribute("message",
                    "最该管理员用户不能删除");
            redirectAttributes.addFlashAttribute("messageType", "warning");
        } else {
            //删除用户和角色的关联
            userService.deleteById(id);
        }
        return ssoConfig.getRedirectWithPath("/sys/user/list");
    }

    @Sign
    @ResponseBody
    @RequestMapping("/checkLoginName")
    public boolean checkLoginName(@RequestParam String loginName, @RequestParam String oldLoginName) {
        if (loginName != null && loginName.equals(oldLoginName)) {
            return true;
        } else if (loginName != null) {
            User user = new User();
            user.setLoginName(loginName);
            List<User> list = userService.selectExample(user);
            return list.isEmpty();
        }
        return false;
    }
}
